package com.example.recyclerview2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    private Context context;
    private String[] text;
    private OnItemClickListener listener;

    Adapter(Context context, String[] text, OnItemClickListener listener) {//把接口传过来
        this.context = context;
        this.text = text;
        this.listener = listener;
    }

    @Override
    public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item, parent, false));
    }

    @Override
    public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
        holder.textView.setText(text[position]);
        holder.button.setText("第"  + position  +  "个按钮");
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClick(position);//点击按钮时执行接口
            }
        });
    }

    @Override
    public int getItemCount() {
        return text.length;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private TextView textView;
        private Button button;

        public ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.rv_text);
            button = itemView.findViewById(R.id.rv_btn);
        }
    }

    public interface OnItemClickListener {//创建一个接口
        void onClick(int position);//参数自己写
    }
}
